<?php
declare (strict_types = 1);
namespace app\business;

use think\Exception;
use think\facade\Log;

class Category {
    protected $model;

    public function __construct() {
        $this->model = new \app\model\mysql\Category();
    }

    public function list($currentId = 0, $fields, $where = []) {

        try{
            $result = $this->model->list($currentId, $fields, $where);
            if ($result && $result->count() > 0) {
                return $result->toArray();
            }
            return [];
        }catch (Exception $e){
            Log::error($e->getMessage());
            return [];
        }
    }

    public function pageList($page = 1, $data = []) : array {
        $where = [
            ["is_delete", "<>", 1]
        ];
        $order = [
            "list_order" => "ASC",
            "id" => "DESC",
        ];
        $pageSize = 2;
        $fields = "";

        if (isset($data["where"])){
            $where = array_merge($where, $data["where"]);
        }
        if (isset($data["order"])){
            $order = array_merge($order, $data["order"]);
        }
        if (isset($data["pageSize"])) {
            $pageSize = $data["pageSize"];
        }
        if (isset($data["fields"])) {
            $fields = $data["fields"];
        }

        $paginate = [
            "list_rows" => $pageSize,
            "page" => $page
        ];
        try{
            $result = $this->model->pageList($paginate, $where, $order, $fields);
            if ($result && $result->count() > 0) {
                return $result->toArray();
            }

            return [];
        }catch (Exception $e){
            Log::error($e->getMessage());
            return [];
        }
    }

    public function load($id = 0) : array {
        if ($id <= 0) {
            return [];
        }

        try{
            $result = $this->model
                ->where("is_delete", "<>", 1)->find($id);
            if ($result && $result->id > 0) {
                return $result->toArray();
            }

            return [];
        }catch (Exception $e){
            Log::error($e->getMessage());
            return [];
        }
    }

    public function getCountListByPids($pidArr = []) :array {
        if (empty($pidArr)) {
            return [];
        }
        try{
            return $this->model->getCountListByPids($pidArr);
        }catch (Exception $e){
            Log::error($e->getMessage());
            return [];
        }
    }

    public function getListByPid($pid = 0, $field = "id, name,  pid") : array {
        $categories = [];
        try{
            $categories = $this->model->getListByPid($pid, $field);
        }catch (Exception $e){
            Log::error($e->getMessage());
        }

        return $categories;
    }
}